package com.qingyun.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局过滤器 - 记录请求日志
 */
@Slf4j
@Component
public class GlobalLogFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 记录请求开始时间
        long startTime = System.currentTimeMillis();
        
        // 记录请求信息
        log.info("Gateway Request: {} {} from {}", 
            request.getMethod(), 
            request.getURI(), 
            request.getRemoteAddress());

        // 添加请求ID到响应头
        String requestId = java.util.UUID.randomUUID().toString();
        response.getHeaders().add("X-Request-Id", requestId);

        return chain.filter(exchange).then(
            Mono.fromRunnable(() -> {
                long endTime = System.currentTimeMillis();
                long duration = endTime - startTime;
                
                log.info("Gateway Response: {} {} - {}ms, Status: {}", 
                    request.getMethod(), 
                    request.getURI(), 
                    duration,
                    response.getStatusCode());
            })
        );
    }

    @Override
    public int getOrder() {
        return -1; // 优先级最高
    }
}
